import { LData, PriorityEnum, Task } from './type';
import eventEmitter from './eventEmitter';

let id = 0;

/**
 * 缓冲区: 存储任务，并提供 API 让调度器获取数据
 */
export default class Storage {
  tasks: Task[];

  maxTasks: number;

  constructor(props: { maxTasks: number }) {
    this.tasks = [];
    this.maxTasks = props.maxTasks;
  }

  /**
   * 往缓冲区 push 任务
   *
   * @param {LData} data
   * @return {*}
   * @memberof Storage
   */
  push(data: LData[], priority: PriorityEnum) {
    if (priority === PriorityEnum.HIGH) {
      eventEmitter.emit(PriorityEnum.HIGH, data);
      return;
    }
    const tasks = data.map((d) => ({ id: ++id, data: d, count: 1 }));
    this.tasks = this.tasks.concat(tasks);
    // 同步检查是否超容
    eventEmitter.emit(PriorityEnum.LOW);
  }

  /**
   * 取出缓冲区的任务
   *
   * @param {number} n
   * @return {*}
   * @memberof Storage
   */
  pop(n: number) {
    const tasks = this.tasks.slice(0, n);
    this.tasks = this.tasks.slice(n);
    return tasks;
  }

  // 判断是否超容量
  isFull() {
    return this.tasks.length >= this.maxTasks;
  }

  // 判断是否有任务
  hasTasks() {
    return this.tasks.length > 0;
  }
}
